# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from collections import OrderedDict
import hashlib

from .pair_base import PairBase

class RawAndCodeBlock(PairBase):
    """
    Raw and CodeBlock
    raw字符串(pre文本和html)和代码块解析
    """
    def __init__(self, content, key_char, cache_key):
        super(RawAndCodeBlock, self).__init__(content, key_char, cache_key, 3)

    @property
    def states(self):
        return {
            'normal': 0, # init, goend -->
            'prebegin': 1, # ' normal -->
            'gobegin': 2, # '' prebegin -->
            'cache': 3, # ''' gobegin -->
            'ignore': 4, # \ ignore -->
            'preend': 5, # cache -->
            'goend': 6 # preend -->
        }

    def parse(self):
        '''执行解析操作'''
        # init state is normal
        state = self.states['normal']
        i = 0
        start = None
        end = None
        store = OrderedDict()
        while i < len(self.content):
            _c = self.content[i]
            # print(_c, self._getStateKey(state))
            if _c == self.key_char:
                if state == self.states['normal']:
                    state = self.states['prebegin']
                elif state == self.states['prebegin']:
                    state = self.states['gobegin']
                elif state == self.states['gobegin']:
                    state = self.states['cache']
                    start = i-2
                elif state == self.states['ignore']:
                    state = self.states['cache']
                elif state == self.states['cache']:
                    state = self.states['preend']
                elif state == self.states['preend']:
                    state = self.states['goend']
                elif state == self.states['goend']:
                    state = self.states['normal']
                    end = i + 1
                    if not start is None and not end is None:
                        _k = '@{0}_[{1}_{2}]'.format(
                            self.cache_key,
                            str(start),
                            str(end)
                        )
                        try:
                            _k_md5 = hashlib.md5(_k).hexdigest()
                        except Exception as ex:
                            _k_md5 = hashlib.md5(_k.encode('utf-8', 'ignore')).hexdigest()
                        _k = '{0}{{{1}}}'.format(
                            '$',
                            _k_md5
                        )
                        store[_k] = {
                            'content': self.content[start : end],
                            'start': start,
                            'end': end
                        }
                    start = None
                    end = None
            else:
                if state == self.states['cache'] or state == self.states['ignore']:
                    if _c == self.escape_char:
                        state = self.states['ignore']
                elif state == self.states['prebegin'] or  state == self.states['gobegin']:
                    state = self.states['normal']
                elif state == self.states['preend'] or  state == self.states['goend']:
                    state = self.states['cache']
            i += 1

        return self._wrapperResult(store)